local xDaemon = {}

print("start Daemon... HEAP:"..node.heap())
who="ESP8266_SWITCH"

apconfig="apconfig"
apclib=nil
isapconfig=1
o=1

function xDaemon.oncallback()
	if package.loaded["xgpio"]==nil then
		xt=require("xgpio")
	end
	if o==1 then
		xt=package.loaded["xgpio"]
		print("oncall xgpio")
		--xt.printc()
	end
	if package.loaded["server"]==nil then
		xs=require("server")
		xs.start()
		print("server loaded. HEAP:"..node.heap())
	end
end

function xDaemon.oncheck()
	if wifi.sta.getip()=="0.0.0.0" then
		if isapconfig==0 then
			node.restart()
		end
		if apclib==nil then
			apclib=require(apconfig)
			if apclib==nil then
				print("APConfig loaded failed. HEAP:"..node.heap())
			else
				apclib.startconfig()
				print("APConfig loaded. HEAP:"..node.heap())
			end
		end
	else
		isapconfig=0
		if apclib~=nil then
			apclib=nil
			package.loaded[apconfig]=nil
			apconfig=nil
			print("APConfig unloaded. HEAP:"..node.heap())
		end
		xDaemon.oncallback()
	end
end

function xDaemon.start()
	tmr.alarm(0,5000, 1, xDaemon.oncheck)
end

return xDaemon
